package cn.bdqn.page2;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * 套餐变更
 */
public class Change {
	// 因为所有的方法都需要DOM树
	static Document document = null;
	static Element root = null;

	// 保存用户信息类
	public static void save(String path) {
		OutputFormat format = null;
		XMLWriter writer = null;
		try {
			format = OutputFormat.createPrettyPrint();
			writer = new XMLWriter(new FileWriter("UserMessage.xml"), format);
			writer.write(document);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	// 更换套餐
	public void change(String phone) throws DocumentException {
		Scanner input = new Scanner(System.in);
		System.out.println("**********套餐变更************");
		System.out.println("1、话唠套餐\t2、网虫套餐\t3、超人套餐\n请选择（序号）：");
		int num = input.nextInt();
		SAXReader reader = new SAXReader();
		document = reader.read("UserMessage.xml");
		root = (Element) document.getRootElement();
		Iterator itUser = root.elementIterator();
		while (itUser.hasNext()) {
			Element user = (Element) itUser.next();
			// 不会找到你指定的那个东西
			if (phone.equals(user.attributeValue("id"))) {
				if (user.attributeValue("longCall").equals("500分钟") && num == 1) {// 话唠套餐
					System.out.println("对不起，您已经是该套餐用户，无需换套餐！");
				} else if (user.attributeValue("longCall").equals("0分钟")) {
					System.out.println("对不起，您已经是该套餐用户，无需换套餐！");
				} else if (user.attributeValue("longCall").equals("200分钟")) {
					System.out.println("对不起，您已经是该套餐用户，无需换套餐！");
				}
			}

			switch (num) {
			case 1:
				user.attribute("longCall").setValue("500分钟");
				user.attribute("internetTraffic").setValue("0G");
				user.attribute("shortMessage").setValue("30条");
				System.out.println("套餐变更成功！");
				return;
			case 2:
				user.attribute("longCall").setValue("0分钟");
				user.attribute("internetTraffic").setValue("3G");
				user.attribute("shortMessage").setValue("0条");
				System.out.println("套餐变更成功！");
				return;
			case 3:
				user.attribute("longCall").setValue("200分钟");
				user.attribute("internetTraffic").setValue("1G");
				user.attribute("shortMessage").setValue("50条");
				System.out.println("套餐变更成功！");
				return;
			}
		}

		save("UserMessage.xml");
	}
}
